/**
 * 
 */
package org.flycloud.web.platform.sevice.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.flycloud.web.platform.dao.MenuDao;
import org.flycloud.web.platform.dao.UserDao;
import org.flycloud.web.platform.entity.Menu;
import org.flycloud.web.platform.entity.Permission;
import org.flycloud.web.platform.entity.Role;
import org.flycloud.web.platform.entity.User;
import org.flycloud.web.platform.sevice.IPlatformService;
import org.flycloud.web.sso.common.UserSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class PlatformService implements IPlatformService {

	@Autowired
	private MenuDao menuDao;

	@Resource
	private UserDao userDao;

	@Override
	public UserSession login(String username, String password) {
		User ui = userDao.findByUsername(username);

		if (ui.getStatus() == null || !ui.getStatus().equals("enabled")) {
			return null;
		}

		UserSession us = new UserSession();
		us.setId(ui.getUsername());
		us.setCharacterName(ui.getRealname());
		us.setUserName(ui.getUsername());

		Set<String> perms = new HashSet<>();

		for (Role r : ui.getRoles()) {
			us.addRole(r.getId());
			for (Permission p : r.getPermissions()) {
				fill(perms, p);
			}
		}

		System.out.println(us.getUserName());
		for (String p : perms) {
			us.addPermission(p);
			System.out.println(p);
		}

		return us;
	}

	private void fill(Set<String> perms, Permission p) {
		if (!perms.contains(p.getId())) {
			perms.add(p.getId());
			for (Permission ps : p.getChildren()) {
				fill(perms, ps);
			}
		}
	}

	@Override
	public List<Menu> getMenuList(UserSession us) {
		List<Menu> all = menuDao.findRoots();
		process(all, us.getPermissions());
		return all;
	}

	private void process(List<Menu> ms, List<String> perms) {
		Set<Menu> ss = new HashSet<>();
		for (Menu m : ms) {
			if (!perms.contains("menu." + m.getId())) {
				ss.add(m);
			}
		}
		for (Menu m : ss) {
			ms.remove(m);
		}
		for (Menu m : ms) {
			process(m.getChildren(), perms);
		}
	}

}
